package com.nine.pesys.util.interceptor;

import com.nine.pesys.model.entity.Role;
import com.nine.pesys.model.entity.User;
import com.nine.pesys.model.service.RoleService;
import com.nine.pesys.model.service.UserService;
import com.nine.pesys.util.annotation.Privilege;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by L先森 on 2014/12/27.
 */
@SuppressWarnings("all")
public class PrivilegeItc extends AbstractInterceptor{
    private Set<Role> roles = new HashSet<Role>();
    @Autowired
    private RoleService roleService;
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
//        检查类上是不是有权限注解
        System.out.println("============权限拦截器===========");
        Class clazz = actionInvocation.getAction().getClass();
        String methodName = actionInvocation.getProxy().getMethod();
        Method currentMethod = clazz.getMethod(methodName);
        String[] privilegeName = {};
//        如果类上有注解
        System.out.println(clazz.toString()+"======================");
        if(clazz.isAnnotationPresent(Privilege.class)){
//            返回Privilege类型的注解
            Privilege privilege = (Privilege)clazz.getAnnotation(Privilege.class);
            privilegeName = privilege.value();
            System.out.println(privilegeName+"====Privilege.class========");
        }
//        如果方法上有注解
        if (currentMethod.isAnnotationPresent(Privilege.class)){
            Privilege privilege = currentMethod.getAnnotation(Privilege.class);
            privilegeName = privilege.value();
        }
        HttpSession session = ServletActionContext.getRequest().getSession();
        User user = (User)session.getAttribute("user");
        if (user!=null){
//            roles = new HashSet<Role>(this.roleService.getByUser(user));
           roles = user.getRoles();
           System.out.println(user.getName()+"============333333333===============");
        }
//        双循环来验证权限
        if (roles!=null&&roles.size()>0){
            for (Role role:roles){
                for(String priName:privilegeName){
                    if (role.getName().equals(priName))
                        return actionInvocation.invoke();
                }
            }
        }
//        ActionContext.getContext().put("message","对不起你没有这个权限");
//        return "error";
        return actionInvocation.invoke();
    }


}
